import React, { Component } from 'react'
import './header.scss'
import {connect} from 'react-redux'
import {Button,Cascader} from 'antd'

import BreadCrumb from '../../common/BreadCrumb'
import {logout} from '../../../redux/actions/user'
import api from '../../../api'
import {formateDate} from '../../../utils/dateUtils'
import residences from '../../../api/residen.json'

class Header extends Component {
    state = {
        currentTime: formateDate(Date.now()), // 当前时间字符串
        weather: {}, // 天气的文本
      }
    loginOut = ()=>{
        this.props.logout()
    }
    changeLocation = async (value)=>{
        console.log(value);
        const {weather} = this.state
        let res = await api.weather.rqWeather(value[1])
        console.log(res.weather);
        this.setState({weather:res.weather[0]})
    }
    getTime = () => {
        // 每隔1s获取当前时间, 并更新状态数据currentTime
        this.intervalId = setInterval(() => {
          const currentTime = formateDate(Date.now())
          this.setState({currentTime})
        }, 1000)
      }
    async componentDidMount(){
        const {weather} = this.state
        let res = await api.weather.rqWeather("浙江省杭州市余杭区")
        console.log(res.weather);
        this.setState({weather:res.weather[0]})
        this.getTime()
    }
    render() {
        const {username,avatar} = JSON.parse(this.props.user.data)[0]
        const {currentTime,weather} = this.state
        return (
            <div id="header">
                <div className="header-top">
                    <BreadCrumb></BreadCrumb>
                    <div className="user-info">
                        <div className="user flex_start">欢迎，<div className="icon"><img src={avatar} alt=""/></div>{username}</div>
                        <Button type="link" onClick={this.loginOut}>退出</Button>
                    </div>
                </div>
                <div className="weather flex_start">
                    <p>{currentTime}</p>
                    <p><span>气温：</span>{weather.temp}</p>
                    <p><span>天气：</span>{weather.weather}</p>
                    <p><span>风向：</span>{weather.wind}{weather.p}</p>
                    <p><span>地点:</span><Cascader defaultValue={['浙江省', '杭州市', '余杭区']} fieldNames={{ label: 'ssqname', value: 'ssqname' }} options={residences.provinces.province} className="loaction" onChange={this.changeLocation}/></p>
                </div>
            </div>
        )
    }
}
export default connect(
    state =>({
        user:state.user
    }),
   {logout}
)(Header)